<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="WebGL," />










<meta name="description" content="一、WebGL基本概念 WebGL (Web Graphics Library) is a JavaScript API for rendering interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins. WebGL does so by introducing an">
<meta name="keywords" content="WebGL">
<meta property="og:type" content="article">
<meta property="og:title" content="WebGL漫游之旅（一）">
<meta property="og:url" content="http://srtian96.gitee.io/blog/2019/02/17/WebGL漫游之旅（一）/index.html">
<meta property="og:site_name" content="Srtian&#39;Blog">
<meta property="og:description" content="一、WebGL基本概念 WebGL (Web Graphics Library) is a JavaScript API for rendering interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins. WebGL does so by introducing an">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/4116027-a3e4b13954be668d.PNG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2019-03-21T04:56:22.702Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="WebGL漫游之旅（一）">
<meta name="twitter:description" content="一、WebGL基本概念 WebGL (Web Graphics Library) is a JavaScript API for rendering interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins. WebGL does so by introducing an">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/4116027-a3e4b13954be668d.PNG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://srtian96.gitee.io/blog/2019/02/17/WebGL漫游之旅（一）/"/>





  <title>WebGL漫游之旅（一） | Srtian'Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Srtian'Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">It's better to burn out than to fade away</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2019/02/17/WebGL漫游之旅（一）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">WebGL漫游之旅（一）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-02-17T19:17:39+08:00">
                2019-02-17
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/可视化/" itemprop="url" rel="index">
                    <span itemprop="name">可视化</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,505
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  10
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="一、WebGL基本概念"><a href="#一、WebGL基本概念" class="headerlink" title="一、WebGL基本概念"></a>一、WebGL基本概念</h3><blockquote>
<p>WebGL (Web Graphics Library) is a JavaScript API for rendering interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins. WebGL does so by introducing an API that closely conforms to OpenGL ES 2.0 that can be used in HTML5 canvas elements.  –MDN</p>
</blockquote>
<p>以上是MDN对于WebGL的描述，简单来说，WebGL 就是一组基于 JavaScript 语言的图形规范，浏览器厂商按照这组规范进行实现，为 Web 开发者提供一套3D图形相关的 API。</p>
<p>我们可以通过这些API直接使用JavaScript直接和GPU进行通信，从而实现一些非常炫酷的图形。而webGL是在GPU上运行的，因此我们需要使用能够在GPU上运行的代码，首先我们需要一种叫做GLSL的语言，它是一种和C or CPP类似的强类型的语言，所以写起来很麻烦（这也是很多人吐槽WebGL的一个方面），其次这样的代码需要提供成对的方法，每对方法中，一个叫做顶点着色器，一个叫做片段着色器，这样的每一对组合起来就称作一个program(着色程序)。其中顶点着色器的作用是计算顶点的位置，根据计算出来的一系列的顶点的位置，WebGL就可以对点、线以及三角形在内的一些图元进行光栅化处理。当对这些图元进行光栅化处理的时候就需要使用片段着色器方法了，它的作用是计算出当前绘制图元中的每个像素的颜色值。</p>
<h4 id="1-1-什么是GLSL"><a href="#1-1-什么是GLSL" class="headerlink" title="1.1 什么是GLSL"></a>1.1 什么是GLSL</h4><p>上面我们提到了GLSL，其中文的意思是OpenGL着色语言，它是用来在 OpenGL 编写着色器程序的语言，全称为 OpenGL Shading Language。而着色器程序则是在GPU上运行的简短的程序，代替了GPU固定渲染管线的一部分，使GPU渲染过程中的某些部分允许开发者通过编程进行控制。</p>
<p>而GPU渲染过程中具体允许我们对其进行控制的部分有以下几个方面：</p>
<ul>
<li>JavaScript程序，处理着色器所需要的顶点坐标、法向量、颜色、纹理等。</li>
<li>顶点着色器，接受JavaScript传递过来的顶点信息，将顶点绘制到对应的坐标。</li>
<li>图元装配阶段，将三个顶点装配成指定的图元类型。</li>
<li>光栅化阶段，将三角形内部区域用空像素进行填充。</li>
<li>片元着色器，为三角形内部的像素填充颜色信息。</li>
</ul>
<h4 id="1-2-WebGL工作流程"><a href="#1-2-WebGL工作流程" class="headerlink" title="1.2 WebGL工作流程"></a>1.2 WebGL工作流程</h4><p>上面对WebGL的基本情况进行了一个简单的概述，但好像也没有解答webGL将3D模型显示到屏幕上的工作原理及流程。其实这个过程就好比富士康工作流水一样，按照既定的工作流程来对原材料进行加工，从而生产出完整的产品。WebGL大致也是如此，按照工作流水线的方式，将3D的模型数据渲染到2D屏幕上的，这个渲染方式的过程一般被称之为图形管线或者渲染管线。</p>
<p>上面我们又说到过点、线、三角形这些基本图元，但我们经常看见很多通过WebGL所绘制出来的诸如球体、圆柱、各式的立方体等模型，也看见了很多炫酷、复杂的模型，很显然这些并不属于这些基本图元里面，但其实这些模型本质上都是有一个个顶点组成的，GPU将这些点用三角线图元绘制成一个个微小的小平面，然后通过这些小平面的互相连接，来组成各种各样的的立体模型。因此通常来说，我们首先要做的就是创建组成模型的顶点数据。</p>
<p>一般情况下，最初的顶点坐标是相对于模型中心的，我们需要对顶点坐标按照一系列步骤执行模型转换、视图转换、投影转换，在通过这一系列的转换后的坐标叫做裁剪空间坐标，这个坐标才是WebGL可以接受的坐标。我们把最后的变换矩阵和原始顶点坐标传递给GPU，GPU的渲染管线然后对他们执行流水工作，主要过程如下：</p>
<ol>
<li>进入顶点着色器，利用GPU的并行计算优势对顶点逐个进行坐标变换。</li>
<li>进入图元装配阶段，将会顶点按照图元类型组装成图形</li>
<li>进入光栅化阶段，光栅化阶段对图像用不包含颜色信息的像素进行填充</li>
<li>进入着色器阶段，为像素着色，并最终显示在屏幕上</li>
</ol>
<h3 id="二、WebGL初体验"><a href="#二、WebGL初体验" class="headerlink" title="二、WebGL初体验"></a>二、WebGL初体验</h3><p>上面将WebGL的大致情况进行了描述，下面就是真刀实枪的来搞事情了，和Three.js一样（这是废话。），我们在使用WebGL进行开发的时候首先需要使用canvas，我们可以再HTML文件里的这样声明一个canvas。顺便对浏览器对canvas的支持情况进行一个检查：<br><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">body</span> <span class="attr">onload</span>=<span class="string">"main()"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">canvas</span> <span class="attr">id</span>=<span class="string">"glcanvas"</span> <span class="attr">width</span>=<span class="string">"640"</span> <span class="attr">height</span>=<span class="string">"480"</span>&gt;</span></span><br><span class="line">    Your browser doesn't appear to support the HTML5 <span class="tag">&lt;<span class="name">code</span>&gt;</span>&amp;lt;canvas&amp;gt;<span class="tag">&lt;/<span class="name">code</span>&gt;</span> element.</span><br><span class="line">  <span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>webGL应用主要包含两个要素：JavaScript程序和着色器程序。首先让我们来准备着色器程序，使用GLSL编写顶点着色器和片元着色器。</p>
<p>顶点着色器的任务我们在上面已经说了，它主要是告诉GPU我们所要形成的图形在裁剪坐标系的位置，下面这个代码就是告诉GPU我们需要在裁剪坐标系的原点，即屏幕中心画一个大小为20的点：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> main()&#123;</span><br><span class="line">    <span class="comment">//声明顶点位置</span></span><br><span class="line">    gl_Position = vec4(<span class="number">0.0</span>, <span class="number">0.0</span>, <span class="number">0.0</span>, <span class="number">1.0</span>)</span><br><span class="line">    <span class="comment">//声明所需绘制的点的大小</span></span><br><span class="line">    gl_PointSize = <span class="number">20.0</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当顶点着色器中的数据经过图元装配和光栅化之后，来到了片元着色器，从而通过片元着色器将像素渲染成我们所需要的颜色：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> main()&#123;</span><br><span class="line">    <span class="comment">//设置像素的填充颜色为红色。</span></span><br><span class="line">    gl_FragColor = vec4(<span class="number">1.0</span>, <span class="number">0.0</span>, <span class="number">0.0</span>, <span class="number">1.0</span>) </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在这里，gl_Position、gl_PointSize、gl_FragColor 是 GLSL 的内置属性：</p>
<ul>
<li>gl_Position：顶点的裁剪坐标系坐标，包含X、Y、Z、W四个坐标分量。顶点着色器接收坐标后，会对它进行透视除法，即将各个分量同时除以 W，从而转换成 NDC 坐标，NDC 坐标每个分量的取值范围都在（-1, 1）之间，GPU 获取这个属性值作为顶点的最终位置进行绘制。</li>
<li>gl_FragColor：片元（像素）颜色，包含 R, G, B, A 四个颜色分量，且每个分量的取值范围在（0,1）之间，GPU 会获取这个值，作为像素的最终颜色进行着色。</li>
<li>gl_PointSize：绘制到屏幕的点的大小，gl_PointSize只有在绘制图元是点的时候才会生效。</li>
</ul>
<p>然后我们就可以着手写我们的JavaScript部分的代码了，首先我们需要获取webGL的绘图环境：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> canvas = <span class="built_in">document</span>.querySelector(<span class="string">'#canvas'</span>)</span><br><span class="line"><span class="keyword">const</span> gl = canvas.getContext(<span class="string">'webgl'</span>)</span><br></pre></td></tr></table></figure>
<p>然后创建顶点着色器：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取顶点着色器源码</span></span><br><span class="line"><span class="keyword">const</span> vertexShaderSource = <span class="built_in">document</span>.querySelector(<span class="string">'#vertexShader'</span>).innerHTML</span><br><span class="line"><span class="comment">// 创建顶点着色器对象</span></span><br><span class="line"><span class="keyword">const</span> vertexShader = gl.createShader(gl.VERTEX_SHADER)</span><br><span class="line"><span class="comment">// 将源码分配给顶点着色器对象</span></span><br><span class="line">gl.shaderSource(vertexShader, vertexShaderSource)</span><br><span class="line"><span class="comment">// 编译顶点着色器程序</span></span><br><span class="line">gl.compileShader(vertexShader)</span><br></pre></td></tr></table></figure>
<p>再就是创建片元着色器：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取片元着色器源码</span></span><br><span class="line"><span class="keyword">const</span> fragmentShaderSource = <span class="built_in">document</span>.querySelector(<span class="string">'#fragmentShader'</span>).innerHTML</span><br><span class="line"><span class="comment">// 创建片元着色器程序</span></span><br><span class="line"><span class="keyword">const</span> fragmentShader = gl.createShader(gl.FRAGMENT_SHADER)</span><br><span class="line"><span class="comment">// 将源码分配给片元着色器对象</span></span><br><span class="line">gl.shaderSource(fragmentShader, fragmentShaderSource)</span><br><span class="line"><span class="comment">// 编译片元着色器</span></span><br><span class="line">gl.compileShader(fragmentShader)</span><br></pre></td></tr></table></figure>
<p>以上就将我们的着色器对象创建完成了，接下来我们就可以创建着色器程序了：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//创建着色器程序</span></span><br><span class="line"><span class="keyword">const</span> program = gl.createProgram()</span><br><span class="line"><span class="comment">//将顶点着色器挂载在着色器程序上。</span></span><br><span class="line">gl.attachShader(program, vertexShader)</span><br><span class="line"><span class="comment">//将片元着色器挂载在着色器程序上。</span></span><br><span class="line">gl.attachShader(program, fragmentShader)</span><br><span class="line"><span class="comment">//链接着色器程序</span></span><br><span class="line">gl.linkProgram(program)</span><br></pre></td></tr></table></figure>
<p>我们在进行webgl开发的时候，可能会在一个WebGL应用里包含多个program，因此我们在使用某狗program绘制前，要先启用它，才能进行绘制：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">gl.useProgram(program)</span><br><span class="line"><span class="comment">// 绘制</span></span><br><span class="line">gl.clearColor(<span class="number">0.0</span>, <span class="number">0.0</span>, <span class="number">0.0</span>, <span class="number">1.0</span>)</span><br><span class="line">gl.clear(gl.COLOR_BUFFER_BIT)</span><br><span class="line">gl.drawArrays(gl.POINTS, <span class="number">0</span>, <span class="number">1</span>)</span><br></pre></td></tr></table></figure>
<p>如此我们完成了我们的第一个webGL代码了，效果如下：<br><img src="https://upload-images.jianshu.io/upload_images/4116027-a3e4b13954be668d.PNG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="webGL1.PNG"><br>完整代码如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line">&lt;body onload=<span class="string">"main()"</span>&gt;</span><br><span class="line">	&lt;!-- 顶点着色器源码 --&gt;</span><br><span class="line">	&lt;script type=<span class="string">"shader-source"</span> id=<span class="string">"vertexShader"</span>&gt;</span><br><span class="line">	 <span class="keyword">void</span> main()&#123;</span><br><span class="line">  		<span class="comment">//声明顶点位置</span></span><br><span class="line">  		gl_Position = vec4(<span class="number">0.0</span>, <span class="number">0.0</span>, <span class="number">0.0</span>, <span class="number">1.0</span>);</span><br><span class="line">  		<span class="comment">//声明要绘制的点的大小。</span></span><br><span class="line">  		gl_PointSize = <span class="number">10.0</span>;</span><br><span class="line">  	&#125;</span><br><span class="line">	&lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">	</span></span><br><span class="line"><span class="regexp">	&lt;!-- 片元着色器源码 --&gt;</span></span><br><span class="line"><span class="regexp">	&lt;script type="shader-source" id="fragmentShader"&gt;</span></span><br><span class="line"><span class="regexp">	 void main()&#123;</span></span><br><span class="line"><span class="regexp">	 	/</span><span class="regexp">/设置像素颜色为红色</span></span><br><span class="line"><span class="regexp">		gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); </span></span><br><span class="line"><span class="regexp">	&#125;</span></span><br><span class="line"><span class="regexp">	&lt;/</span>script&gt;</span><br><span class="line">	&lt;canvas id=<span class="string">"canvas"</span> width=<span class="string">"640"</span> height=<span class="string">"480"</span>&gt;</span><br><span class="line">	Your browser doesn<span class="string">'t appear to support the HTML5 &lt;code&gt;&amp;lt;canvas&amp;gt;&lt;/code&gt; element.</span></span><br><span class="line"><span class="string">	&lt;/canvas&gt;</span></span><br><span class="line"><span class="string">&lt;script type="text/javascript"&gt;</span></span><br><span class="line"><span class="string">function main() &#123;</span></span><br><span class="line"><span class="string">	// 获取webGL的绘图环境</span></span><br><span class="line"><span class="string">	const canvas = document.querySelector("#canvas")</span></span><br><span class="line"><span class="string">  	const gl = canvas.getContext("webgl")</span></span><br><span class="line"><span class="string">	// 创建顶点着色器</span></span><br><span class="line">	const vertexShaderSource = document.querySelector('#vertexShader').innerHTML</span><br><span class="line">	<span class="keyword">const</span> vertexShader = gl.createShader(gl.VERTEX_SHADER)</span><br><span class="line">	gl.shaderSource(vertexShader, vertexShaderSource)</span><br><span class="line">	gl.compileShader(vertexShader)</span><br><span class="line">	<span class="comment">// 创建片元着色器</span></span><br><span class="line">	<span class="keyword">const</span> fragmentShaderSource = <span class="built_in">document</span>.querySelector(<span class="string">'#fragmentShader'</span>).innerHTML</span><br><span class="line">	<span class="keyword">const</span> fragmentShader = gl.createShader(gl.FRAGMENT_SHADER)</span><br><span class="line">	gl.shaderSource(fragmentShader, fragmentShaderSource)</span><br><span class="line">	gl.compileShader(fragmentShader)</span><br><span class="line">	<span class="comment">// 创建着色器程序</span></span><br><span class="line">	<span class="keyword">const</span> program = gl.createProgram()</span><br><span class="line">	gl.attachShader(program, vertexShader)</span><br><span class="line">	gl.attachShader(program, fragmentShader)</span><br><span class="line">	gl.linkProgram(program)</span><br><span class="line"></span><br><span class="line">	gl.useProgram(program)</span><br><span class="line">	<span class="comment">// 绘制</span></span><br><span class="line">	gl.clearColor(<span class="number">0.0</span>, <span class="number">0.0</span>, <span class="number">0.0</span>, <span class="number">1.0</span>)</span><br><span class="line">	gl.clear(gl.COLOR_BUFFER_BIT)</span><br><span class="line">	gl.drawArrays(gl.POINTS, <span class="number">0</span>, <span class="number">1</span>)</span><br><span class="line">&#125;</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>body&gt;</span><br></pre></td></tr></table></figure>
<p>参考资料：</p>
<ul>
<li><a href="https://webglfundamentals.org/webgl/lessons/zh_cn/webgl-fundamentals.html" target="_blank" rel="noopener">https://webglfundamentals.org/webgl/lessons/zh_cn/webgl-fundamentals.html</a></li>
<li><a href="https://developer.mozilla.org/zh-CN/docs/Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL" target="_blank" rel="noopener">https://developer.mozilla.org/zh-CN/docs/Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL</a></li>
<li><a href="https://juejin.im/book/5baaf635f265da0ab915cc9f/section/5baaf635e51d450e7125482f" target="_blank" rel="noopener">https://juejin.im/book/5baaf635f265da0ab915cc9f/section/5baaf635e51d450e7125482f</a></li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/WebGL/" rel="tag"># WebGL</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/02/13/Web语义化的那些事儿/" rel="next" title="Web语义化的那些事儿">
                <i class="fa fa-chevron-left"></i> Web语义化的那些事儿
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="Srtian" />
            
              <p class="site-author-name" itemprop="name">Srtian</p>
              <p class="site-description motion-element" itemprop="description">JUST DO IT.</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">59</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">37</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/srtian96" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="shenruotian@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#一、WebGL基本概念"><span class="nav-number">1.</span> <span class="nav-text">一、WebGL基本概念</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-什么是GLSL"><span class="nav-number">1.1.</span> <span class="nav-text">1.1 什么是GLSL</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-WebGL工作流程"><span class="nav-number">1.2.</span> <span class="nav-text">1.2 WebGL工作流程</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二、WebGL初体验"><span class="nav-number">2.</span> <span class="nav-text">二、WebGL初体验</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Srtian</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">102.8k</span>
  
</div>





        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
